package com.woniuxy.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.entity.ResponseResult;
import com.woniuxy.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 作者
 * @create 2025-07-01 16:18
 */

@Slf4j
//@Component
public class LoginFilter2 implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("进入loginFilter");
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        ResponseResult responseResult=null;
        //特殊路径放行
        if (request.getPath().value().contains("/login")) {
            log.info("登录请求，直接放行");
            return chain.filter(exchange);
        }
        log.info("其他请求，验证token");
        String token = request.getHeaders().getFirst("token");
        String fresh = request.getHeaders().getFirst("fresh");
        if (StringUtils.hasLength(token) && JwtUtil.validate(token)) {
            log.info("token有效，验证是否过期");
            if(JwtUtil.isExpire(token)){
                log.info("token有效，过期，验证refresh");
                if (StringUtils.hasLength(fresh) && !JwtUtil.isExpire(fresh)){
                    log.info("refresh有效，没有过期，重新生成双token");
                    token = JwtUtil.create(JwtUtil.getEid(token),JwtUtil.getEname(token));
                    fresh = JwtUtil.createRefresh(JwtUtil.getEid(fresh),JwtUtil.getEname(fresh));
                    response.getHeaders().add("token",token);
                    response.getHeaders().add("fresh",fresh);
                    response.getHeaders().add("Access-Control-Expose-Headers","*");
                    return chain.filter(exchange);
                }else{
                    log.info("refresh无效，拦截");
                    responseResult = new ResponseResult(401, "error", "refresh无效，拦截");
                    return getVoidMono(responseResult, response);
                }
            }else{
                log.info("token有效，没有过期，直接放行放行");
                return chain.filter(exchange);
            }
        }else{
            log.info("token无效，拦截");
            responseResult = new ResponseResult(401, "error", "先登录");
            return getVoidMono(responseResult, response);
        }


    }

    private static Mono<Void> getVoidMono(ResponseResult responseResult, ServerHttpResponse response) {
        response.getHeaders().add("Content-Type", "application/json;charset=utf-8");
        //响应的数据，字符串
        String responseString = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            responseString = objectMapper.writeValueAsString(responseResult);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        //字符串转成字节数组，使用bufferFactory包装
        DataBuffer wrap = response.bufferFactory().wrap(responseString.getBytes());
        //响应数据
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
